"""
utils用于放一些通用的函数
接口返回模板
成功：success函数，传入需要返回的信息
失败：fail函数，传入报错信息和报错编号
user.py
"""

from flask import jsonify, request, g
from src.utils import uuid_util


def attach_request_id():
    """为每个请求附加一个唯一的请求ID"""
    g.request_id = request.headers.get("X-Request-Id", uuid_util.uuid_fixed(16))


def get_request_id():
    """获取当前请求的唯一ID"""
    return getattr(g, "request_id", None)


def success(data=None, msg="成功", request_id=None):
    """请求成功响应"""
    response = {
        "code": "1",
        "data": data if data is not None else {},
        "error_msg": "",
        "msg": msg,
        "request_id": request_id or get_request_id(),
        "status": 200
    }
    return jsonify(response), 200

def success_token(data=None, msg="成功", request_id=None):
    """请求成功响应"""
    response = {
        "code": "1",
        "data": data if data is not None else {},
        "error_msg": "",
        "msg": msg,
        "request_id": request_id or get_request_id(),
        "status": 200
    }
    return jsonify(response)

def fail(msg="", error_msg="", status=500, code="0", data=None, request_id=None):
    """通用失败响应"""
    if msg == "":
        if code == "500":
            msg = "未知错误"
        else:
            msg = error_msg
    response = {
        "code": code,
        "data": data if data is not None else {},
        "error_msg": error_msg or msg,
        "msg": msg,
        "request_id": request_id or get_request_id(),
        "status": status
    }
    return jsonify(response), 200


def param_error(msg="Parameter Error", error_msg="", request_id=None):
    """参数错误响应"""
    return fail(msg=msg, error_msg=error_msg or msg, status=400, code="400", request_id=request_id)


def unauthorized(msg="Unauthorized", error_msg="", request_id=None):
    """未授权或未登录响应"""
    return fail(msg=msg, error_msg=error_msg or msg, status=401, code="401", request_id=request_id)


def not_found(msg="Not Found", error_msg="", request_id=None):
    """资源未找到响应"""
    return fail(msg=msg, error_msg=error_msg or msg, status=404, code="404", request_id=request_id)


def server_error(msg="Internal Server Error", error_msg="", request_id=None):
    """服务器错误响应"""
    return fail(msg=msg, error_msg=error_msg or msg, status=500, code="500", request_id=request_id)
